﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using System.Web.Security;
using EzDesk.Utility.Log;
using Microsoft.International.Converters.PinYinConverter;

namespace EzDesk.Core.ServiceImpl.Services
{
    public class CoreClientLoginService : ICoreClientLoginService
    {
        private static Dictionary<string, string> _userNameDic = new Dictionary<string, string>();

        private IMembershipService _membershipService;
        private ICoreService _coreService;

        public CoreClientLoginService()
        {
            _coreService = new CoreService();
            _membershipService = new AccountMembershipService(Membership.Provider);

            initializeUserNameDic();

            //LogEx.TRACE("ServiceHost - CoreClientLoginService", "初始化CoreClientLoginService");
        }

        public CoreClientLoginService(
            ICoreService coreService,
            IMembershipService membershipService
            )
        {
            _coreService = coreService;
            _membershipService = membershipService;

            initializeUserNameDic();
        }

        private void initializeUserNameDic()
        {
            _userNameDic.Clear();

            //var allUser = _coreService.GetSimpleUserInfos("everyone");
            //if (allUser == null) return;

            //foreach (var simpleUser in allUser)
            //{
            //    // 所有姓名
            //    _userNameDic.SafeAdd(simpleUser.Name, simpleUser.UserName);
            //    // 所有用户名
            //    _userNameDic.SafeAdd(simpleUser.UserName, simpleUser.UserName);

            //    if (simpleUser.Name.IsContainChineseChar())
            //    {
            //        // 所有中文拼音全拼
            //        _userNameDic.SafeAdd(simpleUser.Name.ConvertToFullChinesePinyin(), simpleUser.UserName);
            //        // 所有中文拼音简拼
            //        _userNameDic.SafeAdd(simpleUser.Name.ConvertToSimpleChinesePinyin(), simpleUser.UserName);
            //    }
            //}
        }


        //todo: Login方法不使用WCF身份验证，可直接访问，访问后得到一个WCF所用的Token，用于访问其他的WCF方法
        public UserProfile Login(string userName, string password)
        {
            UserProfile userProfile = null;

            // 验证UserName和pwd
            MembershipProvider membershipProvider = _membershipService.Provider;
            if (membershipProvider.ValidateUser(userName, password))
            {
                // 验证通过
                userProfile = _coreService.GetUserProfileByUserName(userName);
            }
            return userProfile;
        }


        /// <summary>
        /// 从UserNameDic中寻找匹配的用户名
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        public List<SimpleUser> GetUserNameForLogin(string inputString)
        {
            // 限制最多获取5个可用数据
            const int maxCount = 5;

            var userNameList = new List<string>();
            foreach (var key in _userNameDic.Keys)
            {
                if (!key.Contains(inputString)) continue;
                var userName = _userNameDic[key];
                if (!userNameList.Contains(userName))
                {
                    userNameList.Add(userName);
                }
                if (userNameList.Count >= maxCount) break;
            }
            return userNameList
                .Select(p => _coreService.GetSimpleUserInfoByUserName(p))
                .ToList();
        }

    }



    public static class DictionaryExtension
    {
        public static void SafeAdd<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue value)
        {
            if (!dic.ContainsKey(key))
            {
                dic.Add(key,value);
            }
        }
    }

    public static class ChinesePinyinExtension
    {
        /// <summary>
        /// 判断一个字符串中是否包含中文字符
        /// </summary>
        /// <param name="originalStr"></param>
        /// <returns></returns>
        public static bool IsContainChineseChar(this string originalStr)
        {
            return originalStr.Any(ChineseChar.IsValidChar);
        }

        /// <summary>
        /// 将一个字符串转换成汉字全拼
        /// </summary>
        /// <param name="originalStr"></param>
        /// <returns></returns>
        public static string ConvertToFullChinesePinyin(this string originalStr)
        {
            var pinyinBuilder = new StringBuilder();
            foreach (var ch in originalStr)
            {
                // todo: 考虑多音字
                pinyinBuilder.Append(ChineseChar.IsValidChar(ch) ? new ChineseChar(ch).Pinyins[0] : ch.ToString());
            }
            return pinyinBuilder.ToString();
        }

        /// <summary>
        /// 将一个字符串转换成汉字简拼
        /// </summary>
        /// <param name="originalStr"></param>
        /// <returns></returns>
        public static string ConvertToSimpleChinesePinyin(this string originalStr)
        {
            var pinyinBuilder = new StringBuilder();
            foreach (var ch in originalStr)
            {
                // todo: 考虑多音字
                pinyinBuilder.Append(ChineseChar.IsValidChar(ch) ? new ChineseChar(ch).Pinyins[0][0] : ch);
            }
            return pinyinBuilder.ToString();
        }
        
            
    }
}
